<?php

namespace app\model;

use Shopwwi\LaravelCache\Cache;

/**
 * 管理员模型类
 */
class AdminModel extends BaseModel
{
    protected $name = 'admin';


    /**
     * 获取管理员信息(缓存，不包含敏感信息)
     *
     * @param integer $admin_id 管理员id
     * @param boolean $is_update 是否更新缓存
     * @return void
     */
    public static function getDetail($admin_id = 0, $is_update = false)
    {
        if (empty($admin_id)) return [];

        $admin = Cache::get('admin_info_' . $admin_id);

        if (empty($admin) || $is_update) {

            $admin = self::find($admin_id);
            if (empty($admin)){
                Cache::forget('admin_info_' . $admin_id);
                return [];
            }

            $admin = $admin->toArray();
            unset($admin['password']);

            //缓存30天
            Cache::put('admin_info_' . $admin_id, $admin, 86400 * 30);
        }

        return $admin;
    }


    /**
     * 获取管理员所有权限ids
     *
     * @param void $admin_id 管理员id
     */
    public function getRulesIds($admin_id)
    {
        if(empty($admin_id)) return [];

        $rules = Cache::tags('admin_rules')->get('admin_rules_ids_' . $admin_id);
        if (empty($rules)) {
            
            $admin_roles = $this->where("id",$admin_id)->value("roles");
            if(empty($admin_roles)) return [];

            $roles = AdminRolesModel::where("id",$admin_roles)->select();
            if ($roles->isEmpty()) return [];

            $rules = [];
            foreach ($roles as $k => $v) {
                $rules = array_merge($rules, explode(",", $v['rules']));
            }

            //清除数组空内容，清除数组重复内容
            $rules = array_filter(array_unique($rules));
            Cache::tags('admin_rules')->set('admin_rules_ids_' . $admin_id, $rules);
        }

        return $rules;
    }
}
